﻿using Abp;
using System;
using System.Linq;
using ARchGL.Platform.Core;
using Microsoft.EntityFrameworkCore;
using ARchGL.Platform.EntityFrameworkCore;
using ARchGL.Platform.Authorization.Users;

namespace ARchGL.Platform.Migrations.Seed.Tenants
{
    /// <summary>
    /// 初始化系统项目
    /// </summary>
    public class TenantProjectsBuilder
    {
        private readonly TenantDbContext _context;
        private readonly int _tenantId;
        private IGuidGenerator GuidGenerator { get; set; }

        public TenantProjectsBuilder(TenantDbContext context, int tenantId)
        {
            _context = context;
            _tenantId = tenantId;
            GuidGenerator = SequentialGuidGenerator.Instance;
        }

        public void Create()
        {
            CreateSystemProjects();
        }

        private void CreateSystemProjects()
        {
            //Project 项目三标段）
            if (GetById(StaticProjectsValues.Project3Id) == null)
            {
                _context.Projects.Add(GetProject(StaticProjectsValues.Project3Id, "项目三标段", "50002820190815003"));
                _context.SaveChanges();
            }

            //Project 项目二标段）
            if (GetById(StaticProjectsValues.Project2Id) == null)
            {
                _context.Projects.Add(GetProject(StaticProjectsValues.Project2Id, "项目二标段", "50002820190815002"));
                _context.SaveChanges();
            }

            //Project 项目一标段）
            if (GetById(StaticProjectsValues.Project1Id) == null)
            {
                _context.Projects.Add(GetProject(StaticProjectsValues.Project1Id, "项目一标段", "50002820190815001"));
                _context.SaveChanges();
            }
        }

        private Projects GetById(Guid id)
        {
            return _context.Projects.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == _tenantId && r.Id == id);
        }

        private Projects GetProject(Guid id, string name, string code)
        {
            return new Projects
            {
                Id = id,
                Name = name,
                Code = code,
                IsSystem = true,
                CreatorUserId = StaticUserIds.Tenants.Admin
            };
        }
    }
}
